package com.googlecode.delivery.packager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.apache.log4j.Logger;

import com.googlecode.delivery.DeliveryException;
import com.googlecode.delivery.core.impl.EnvironmentHelper;
import com.googlecode.delivery.core.impl.FileUtils;
import com.googlecode.delivery.model.DeploymentUnit;
import com.googlecode.delivery.model.Environment;

/**
 * Packages configuration files containing key/value peers of given environment
 * properties.
 * 
 * @author Stephen Kay
 * 
 */
public class PackageMgr {
	private static final Logger LOGGER = Logger.getLogger(PackageMgr.class);

	private Environment env;
	private Collection<String> tokenizedKeys = null;

	/**
	 * Sets the environment properties.
	 * 
	 * @param env
	 * @throws DeliveryException
	 */
	public PackageMgr(Environment env) throws DeliveryException {
		this.env = env;
		if (getTokenizedKeys().size() < 1) {
			throw new DeliveryException(
					"Environment do not specify any property value with token separator ="
							+ EnvironmentHelper.getTokenSeparator());
		}
	}

	/**
	 * @return
	 */
	protected Collection<String> getTokenizedKeys() {
		if (tokenizedKeys == null) {
			tokenizedKeys = EnvironmentHelper.getTokenizedKeys(env);
			}
		return tokenizedKeys;
	}

	/**
	 * Copies any file from src dir to dest dir if any token found.
	 * 
	 * @param src
	 * @param env
	 * @param destDir
	 * @throws Exception
	 */
	public void copyConfig(File srcDir, File destDir)
			throws DeliveryException, IOException {

		if (!srcDir.exists()) {
			throw new DeliveryException("Input dir does not exist :"
					+ srcDir.getAbsolutePath());
		}
		if (!destDir.exists()) {
			destDir.mkdirs();
		} else if (!destDir.isDirectory() || !destDir.canWrite()) {
			throw new DeliveryException("Destination is not writable :"
					+ destDir.getAbsolutePath(), null);
		}
		//TODO filter resources containing tokens
		
		FileUtils.copy(srcDir, destDir);
	}
	/**
	 * @param environment
	 */
	public void copyEnv(DeliveryTarget target) throws IOException {
		FileUtils.copyFile(env.getEnvFile(), new File(target.getDeliveryDir()
				.getAbsolutePath()
				+ "/" + DeploymentUnit.ENVIRONMENT_FILE_NAME));
	}

	/**
	 * @param sb
	 * @param environment
	 * @return
	 * @throws DeliveryException
	 */
	static Collection<String> findTokens(StringBuffer contents,
			Collection<String> tokenizedKeys) {
		Collection<String> tokenFounds = new ArrayList<String>();
		// iterates over tokenized keys.
		for (Iterator<String> iterator2 = tokenizedKeys.iterator(); iterator2
				.hasNext();) {
			String token = iterator2.next();
			if (contents.indexOf(token) > 0) {
				tokenFounds.add(token);
			}
		}
		return tokenFounds;
	}
}
